package br.com.dojo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import br.com.dojo.bean.Carro;
import br.com.dojo.service.CarroService;


@Controller
@RequestMapping(value = "/carro/**")
public class CarroController {
	
	private static final Logger logger = LoggerFactory
			.getLogger(CarroController.class);	
	
	
	@Autowired
	private CarroService carroService;
	
	List <Carro> carros = new ArrayList<Carro>();
	
	@RequestMapping("/carro/cadastra")
	public ModelAndView cadastro(HttpServletRequest request){
		ModelAndView andView = new ModelAndView("carro/cadastra");
		return andView;
	}
	
	@RequestMapping("/carro/salva")
	public ModelAndView save(@Valid Carro c, BindingResult result){
		ModelAndView andView = new ModelAndView("carro/cadastra");
		
		Carro carro = new Carro();
		
		carro.setPlaca(c.getPlaca());
		carro.setAno(c.getAno());
		carro.setMarca(c.getMarca());
		carro.setQuilometragem(c.getQuilometragem());
		carro.setPatrimonio(c.getPatrimonio());
		//carro.setCategoria(request.getParameter("categoria"));
		//carros.add(carro);
		
		if (result.hasErrors()) {
			System.out.println("Erro mostrado na view.");
			result.getAllErrors();
			
			for (int i = 0; i < result.getAllErrors().size(); i++) {
				System.out.println(result.getAllErrors().get(i).toString());
			}
			
		}
		else {
			//Chama service
			carroService.salvar(carro);			
		}
		
		return andView;
	}
	
	@RequestMapping("/carro/lista")
	public ModelAndView encontraTudo(){
		ModelAndView andView = new ModelAndView("carro/lista");
		carros = carroService.listarCarro();
		andView.addObject("carro", carros);
		return andView;
	}
}
